package com.tcredit.sdk.android;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import org.json.JSONArray;
import org.json.JSONObject;

import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;

public class SendDataTask extends AsyncTask<Void, Void, Boolean> {

    private String uid = "";
    private String host = "";
    private Context context;


    SendDataTask(String userId,String host,Context context) {
        this.uid = userId;
        this.host = host;
        this.context = context;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            JSONObject gps = new JSONObject();
            LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            //获取当前可用的位置控制器
            List<String> list = locationManager.getProviders(true);
            String provider = "";
            if (list.contains(LocationManager.GPS_PROVIDER)) {
                //是否为GPS位置控制器
                provider = LocationManager.GPS_PROVIDER;
            } else if (list.contains(LocationManager.NETWORK_PROVIDER)) {
                //是否为网络位置控制器
                provider = LocationManager.NETWORK_PROVIDER;
            }

            double latitude = 0.0;
            double longitude = 0.0;
            if ("" != provider) {
                Location location = locationManager.getLastKnownLocation(provider);
                if (location != null) {
                    //获取当前位置，这里只用到了经纬度
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }

            }
            gps.put("latitude", latitude);
            gps.put("longitude", longitude);

            JSONObject deviceInfo = new JSONObject();
            TelephonyManager tm = null;
            try {
                tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                if (null != tm) {
                    //运营商名称
                    String networkOperatorName = tm.getNetworkOperatorName();
                    String netWorkCountryIso = tm.getNetworkCountryIso();
                    String networkOperator = tm.getNetworkOperator();
                    deviceInfo.put("networkOperatorName", networkOperatorName);
                    deviceInfo.put("netWorkCountryIso", netWorkCountryIso);
                    deviceInfo.put("networkOperator", networkOperator);

                    String sim = tm.getSimSerialNumber();
                    String imsi = tm.getSubscriberId();
                    //手机号码
                    String number = tm.getLine1Number();
                    deviceInfo.put("sim", sim);
                    deviceInfo.put("imei", tm.getDeviceId());
                    deviceInfo.put("imsi", imsi);
                    deviceInfo.put("number", number);

                }
            } catch (Exception e) {
                deviceInfo.put("sim", "用户拒绝授权");
                deviceInfo.put("imei","用户拒绝授权");
                deviceInfo.put("imsi","用户拒绝授权");
                deviceInfo.put("number", "用户拒绝授权");
            }

            //网络类型
            String apnType = getNetWorkType(context);

            //型号
            String model = Build.MODEL;
            //品牌
            String brand = Build.BRAND;
            //产品名称
            String product = Build.PRODUCT;
            //制造商
            String manufacturer = Build.MANUFACTURER;
            //安卓版本
            String version = Build.VERSION.RELEASE;

            deviceInfo.put("apnType", apnType);
            deviceInfo.put("model", model);
            deviceInfo.put("brand", brand);
            deviceInfo.put("product", product);
            deviceInfo.put("manufacturer", manufacturer);
            deviceInfo.put("version", version);

            JSONArray appList = getAppInfo();

            //分辨率
            String pix = getPix();
            deviceInfo.put("pix", pix);

            //IP地址
            String ipAddress = getIpAddress(context);
            deviceInfo.put("ipAddress", ipAddress);

            JSONObject param = new JSONObject();
            param.put("appId", "aaf7b6dc-0201-4f81-bf7b-9f79e8fb93cb");
            param.put("tokenKey", "a0ee6f99-f850-4fa9-9b15-2fc9bc2cc3ba");


            JSONObject data = new JSONObject();
            data.put("userId", uid);
            data.put("gps", gps);
            data.put("deviceInfo", deviceInfo);
            data.put("appList", appList);
            param.put("param", data);
//                String tcUrl = "https://yzj.tcredit.com/api/iqiyi/sendDevice";
            String tcUrl = host + "/api/iqiyi/sendDevice";
            HttpUrlConnection.getInstance().postString(tcUrl, param.toString(), null);
        } catch (SecurityException e) {
            Log.e("TC_SENDDATA", "Exception", e);
        } catch (Exception e) {
            Log.e("TC_SENDDATA", "Exception", e);
        }
        return true;
    }



    private JSONArray getAppInfo() {
        PackageManager pm = this.context.getPackageManager();
        List<PackageInfo> mPacks = pm.getInstalledPackages(0);
        JSONArray installApps = new JSONArray();
        for (PackageInfo info : mPacks) {
            installApps.put(info.applicationInfo.loadLabel(pm).toString());
        }
        return installApps;
    }

    public static String getNetWorkType(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            String type = networkInfo.getTypeName();

            if (type.equalsIgnoreCase("WIFI")) {
                return "WIFI";
            } else if (type.equalsIgnoreCase("MOBILE")) {
                NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                if (mobileInfo != null) {
                    switch (mobileInfo.getType()) {
                        case ConnectivityManager.TYPE_MOBILE:// 手机网络
                            switch (mobileInfo.getSubtype()) {
                                case TelephonyManager.NETWORK_TYPE_UMTS:
                                case TelephonyManager.NETWORK_TYPE_EVDO_0:
                                case TelephonyManager.NETWORK_TYPE_EVDO_A:
                                case TelephonyManager.NETWORK_TYPE_HSDPA:
                                case TelephonyManager.NETWORK_TYPE_HSUPA:
                                case TelephonyManager.NETWORK_TYPE_HSPA:
                                case TelephonyManager.NETWORK_TYPE_EVDO_B:
                                case TelephonyManager.NETWORK_TYPE_EHRPD:
                                case TelephonyManager.NETWORK_TYPE_HSPAP:
                                    return "3G";
                                case TelephonyManager.NETWORK_TYPE_CDMA:
                                case TelephonyManager.NETWORK_TYPE_GPRS:
                                case TelephonyManager.NETWORK_TYPE_EDGE:
                                case TelephonyManager.NETWORK_TYPE_1xRTT:
                                case TelephonyManager.NETWORK_TYPE_IDEN:
                                    return "2G";
                                case TelephonyManager.NETWORK_TYPE_LTE:
                                    return "4G";
                                default:
                                    return "NONE";
                            }
                    }
                }
            }
        }

        return "NONE";
    }


    public String getPix() {
        WindowManager mWindowManager = (WindowManager) this.context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        mWindowManager.getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels;//获取到的是px，像素，绝对像素，需要转化为dpi
        int height = metrics.heightPixels;
        return width + "," + height;
    }


    /**
     * 获取本机IPv4地址
     *
     * @param context
     * @return 本机IPv4地址；null：无网络连接
     */
    public static String getIpAddress(Context context) {

        try {
            // 获取WiFi服务
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            // 判断WiFi是否开启
            if (wifiManager.isWifiEnabled()) {
                // 已经开启了WiFi
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                int ipAddress = wifiInfo.getIpAddress();
                String ip = intToIp(ipAddress);
                return ip;
            } else {
                // 未开启WiFi
                return getIpAddress();
            }
        } catch (SecurityException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    private static String intToIp(int ipAddress) {
        return (ipAddress & 0xFF) + "." +
                ((ipAddress >> 8) & 0xFF) + "." +
                ((ipAddress >> 16) & 0xFF) + "." +
                (ipAddress >> 24 & 0xFF);
    }

    /**
     * 获取本机IPv4地址
     *
     * @return 本机IPv4地址；null：无网络连接
     */
    private static String getIpAddress() {
        try {
            NetworkInterface networkInterface;
            InetAddress inetAddress;
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                networkInterface = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
            return null;
        } catch (SocketException ex) {
            ex.printStackTrace();
            return null;
        }
    }

}